//
//  CMAnswerCtrl.m
//  CreditManger
//
//  Created by sky on 15/11/9.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "CMAnswerCtrl.h"
#import "CMAnswerProCell.h"
#import "CMQuestionCell.h"
#import "CMGetQuestionParam.h"
#import "CMGetQuestionParser.h"
#import "CMGetQuestionInfo.h"
#import "CMGetQuestionItemInfo.h"
#import "CMGetQuestionAnswerInfo.h"
#import "CMLoginManager.h"
#import "CMSubmitAnswersParam.h"
#import "CMSubmitAnswersParser.h"

@interface CMAnswerCtrl ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *_table;

}

@property (nonatomic , strong)CMGetQuestionInfo *iteminfo;

@property (nonatomic , strong) NSIndexPath *oldindex;

@property (nonatomic , strong) NSIndexPath *newindex;

@end

@implementation CMAnswerCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

-(void)buildLayout{
    
    self.title = @"获取信用报告";
    self.oldindex = [NSIndexPath indexPathForRow:1 inSection:0];
    
    _table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    INIT_TABLE(_table);
    [self.view addSubview:_table];
    [self requestForQuestion];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma - mark submitAnswer

-(void)submitAnswer{
    
    CMGetQuestionItemInfo *oldieminfo = [self.iteminfo.dataAry objectAtIndex:self.oldindex.row - 1];
    NSMutableArray *datamuarr = [NSMutableArray arrayWithArray:self.iteminfo.dataAry];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    int i=0;
    for (CMGetQuestionItemInfo *info in self.iteminfo.dataAry) {
        if (info.selectedAnswer.length > 0) {
            i++;
            CMGetQuestionAnswerInfo *answer = info.answers[[info.selectedAnswer integerValue]];
            [dict setObject:answer.answerKey forKey:info.questionKey];
        }
    }
    if (i==self.iteminfo.dataAry.count)
    {
        oldieminfo.questionStatus = QuestionStatus_Answer;
        [datamuarr replaceObjectAtIndex:self.oldindex.row - 1 withObject:oldieminfo];
        self.iteminfo.dataAry = datamuarr;
        NSIndexPath *oldpath = [NSIndexPath indexPathForRow:self.oldindex.row inSection:0];
        [_table reloadRowsAtIndexPaths:[NSArray arrayWithObjects:oldpath,nil] withRowAnimation:UITableViewRowAnimationFade];
        [self requestSubmitAnswerForQuestionWith:dict];
    }else{
        DISSMISS_ERR(@"请全部答完");
    }
}


#pragma -mark tableViewDelegate


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger x;
    if (self.iteminfo.dataAry.count == 0) {
        x = 0;
    }else{
        x = self.iteminfo.dataAry.count + 1;
    }
    
    return x;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    int x;
    if (indexPath.row == 0) {
        x = 180 / 2;
    }else{
        x = [CMQuestionCell MakeHeightForCellWithShowCmQuestionItemInfo:[self.iteminfo.dataAry objectAtIndex:indexPath.row - 1]];
    }
    return x;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
    static NSString *Prompt = @"Prompt";
    static NSString *Answer = @"Answer";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
    if (indexPath.row == 0) {
        if (!cell) {
            cell = [[CMAnswerProCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Prompt];
            //cell.backgroundColor = [UIColor clearColor];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }else{
        if (!cell) {
            cell = [[CMQuestionCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Answer];
            //cell.backgroundColor = [UIColor clearColor];
        }
        CMQuestionCell *quescell = (CMQuestionCell*)cell;
        quescell.tum = indexPath.row;
        quescell.alliteminfo = [self.iteminfo.dataAry objectAtIndex:indexPath.row - 1];
        
        __weak typeof(self) weakSelf = self;
        quescell.ActionPreviewClickToSelelct = ^(UIButton *btn)
        {
            NSMutableArray *datamuarr = [NSMutableArray arrayWithArray:weakSelf.iteminfo.dataAry];
            CMGetQuestionItemInfo *itemInfo = self.iteminfo.dataAry[indexPath.row-1];
            itemInfo.selectedAnswer = [NSString stringWithFormat:@"%d",(int)btn.tag];
            [datamuarr replaceObjectAtIndex:indexPath.row-1 withObject:itemInfo];
            weakSelf.iteminfo.dataAry = datamuarr;
            NSIndexPath *selectPath=[NSIndexPath indexPathForRow:indexPath.row inSection:0];
            [_table reloadRowsAtIndexPaths:[NSArray arrayWithObjects:selectPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        };

        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
//    
//    CGFloat hue = ( arc4random() % 256 / 256.0 ); //0.0 to 1.0
//    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0,away from white
//    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; //0.5 to 1.0,away from black
//    
//    cell.backgroundColor = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
    cell.backgroundColor = [UIColor clearColor];
    
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CMGetQuestionItemInfo *newinfo = [self.iteminfo.dataAry objectAtIndex:indexPath.row -1];
    CMGetQuestionItemInfo *oldieminfo = [self.iteminfo.dataAry objectAtIndex:self.oldindex.row - 1];

    NSMutableArray *datamuarr = [NSMutableArray arrayWithArray:self.iteminfo.dataAry];
    if (indexPath.row == self.oldindex.row) {
        if (oldieminfo.questionStatus != QuestionStatus_Open) {
            
            oldieminfo.questionStatus = QuestionStatus_Open;
            [datamuarr replaceObjectAtIndex:self.oldindex.row - 1 withObject:oldieminfo];
            self.iteminfo.dataAry = datamuarr;
        
        }else{
            return;
        }
    }else if (oldieminfo.questionStatus == QuestionStatus_Open && oldieminfo.selectedAnswer.length > 0){
        
        oldieminfo.questionStatus = QuestionStatus_Answer;
        [datamuarr replaceObjectAtIndex:self.oldindex.row - 1 withObject:oldieminfo];
        self.iteminfo.dataAry = datamuarr;
        
        newinfo.questionStatus = QuestionStatus_Open;
        [datamuarr replaceObjectAtIndex:indexPath.row - 1 withObject:newinfo];
        self.iteminfo.dataAry = datamuarr;
        
    }else if(oldieminfo.questionStatus == QuestionStatus_Open && newinfo.questionStatus == QuestionStatus_Close){
        
        oldieminfo.questionStatus = QuestionStatus_Close;
        [datamuarr replaceObjectAtIndex:self.oldindex.row - 1 withObject:oldieminfo];
        self.iteminfo.dataAry = datamuarr;
        
        newinfo.questionStatus = QuestionStatus_Open;
        [datamuarr replaceObjectAtIndex:indexPath.row - 1 withObject:newinfo];
        self.iteminfo.dataAry = datamuarr;
    }else if(oldieminfo.questionStatus == QuestionStatus_Open && newinfo.questionStatus == QuestionStatus_Answer && oldieminfo.selectedAnswer.length == 0){
        
        oldieminfo.questionStatus = QuestionStatus_Close;
        [datamuarr replaceObjectAtIndex:self.oldindex.row - 1 withObject:oldieminfo];
        self.iteminfo.dataAry = datamuarr;
        
        newinfo.questionStatus = QuestionStatus_Open;
        [datamuarr replaceObjectAtIndex:indexPath.row - 1 withObject:newinfo];
        self.iteminfo.dataAry = datamuarr;
    }else if(newinfo.questionStatus == QuestionStatus_Answer){
        newinfo.questionStatus = QuestionStatus_Open;
        [datamuarr replaceObjectAtIndex:indexPath.row - 1 withObject:newinfo];
        self.iteminfo.dataAry = datamuarr;
    }
    
    NSIndexPath *oldpath = [NSIndexPath indexPathForRow:self.oldindex.row inSection:0];
    NSIndexPath *newpath = [NSIndexPath indexPathForRow:indexPath.row inSection:0];
    [_table reloadRowsAtIndexPaths:[NSArray arrayWithObjects:oldpath,nil] withRowAnimation:UITableViewRowAnimationFade];
    [_table reloadRowsAtIndexPaths:[NSArray arrayWithObjects:newpath,nil] withRowAnimation:UITableViewRowAnimationFade];
    self.oldindex = indexPath;
}


#pragma mark - addfootview

-(void)addFootView{
    UIView *footview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45 + 15)];
    footview.backgroundColor = [UIColor clearColor];
    UIButton *subbtn = [[UIButton alloc]initWithFrame:CGRectMake(10,0, SCREEN_WIDTH - 20, 45)];
    subbtn.backgroundColor = [LCCommon getColor:HIGH_COLOR];
    [subbtn setTitle:@"提交" forState:UIControlStateNormal];
    subbtn.titleLabel.font = [UIFont systemFontOfSize:15];
    subbtn.layer.cornerRadius = 2.5;
    [subbtn addTarget:self action:@selector(submitAnswer) forControlEvents:UIControlEventTouchUpInside];
    [footview addSubview:subbtn];
    _table.tableFooterView = footview;
}

#pragma mark - request

-(void)requestForQuestion{
    CMGetQuestionParam *param = [[CMGetQuestionParam alloc]init];
    param.loginName = @"";
    param.password  = @"";
    param.authCode  = @"";
    param.token = [CMLoginManager sharedCMLoginManager].currentUserInfo.token;
    param.uid = [CMLoginManager sharedCMLoginManager].currentUserInfo.uid;
    CMGetQuestionParser *parser = [[CMGetQuestionParser alloc]init];
    [NetCenter postDataFromURL:Method_getQuestion params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0)
        {
            CMGetQuestionInfo *info = (CMGetQuestionInfo *)myResult.result;
            self.iteminfo = info;
            [_table reloadData];
            [self addFootView];
        }
        else
        {
            DISSMISS_ERR(myResult.message);
        }

    } failure:^(NSError *error) {
        DISSMISS_ERR([error description]);
    }];
}


-(void)requestSubmitAnswerForQuestionWith:(NSMutableDictionary *)dict{
    CMSubmitAnswersParam *param = [[CMSubmitAnswersParam alloc]init];
    param.uid = [CMLoginManager sharedCMLoginManager].currentUserInfo.uid;
    param.token = [CMLoginManager sharedCMLoginManager].currentUserInfo.token;
    param.loginName = @"";
    param.answers = [self dictionaryToJson:dict];
    CMSubmitAnswersParser *parser = [[CMSubmitAnswersParser alloc]init];
    [NetCenter postDataFromURL:Method_submitAnswers params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0) {
            
        }else if(myResult.code == 2){
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"答题超时,是否重新答题" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
            [alter show];
        }
        else{
            DISSMISS_ERR(myResult.message);
        }
    } failure:^(NSError *error) {
        DISSMISS_ERR([error description]);
    }];
}


#pragma mark - dictforjson

- (NSString*)dictionaryToJson:(NSDictionary *)dict
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

/*
#pragma mark - Navigation
 
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
